<?php
/*
*  Author: Cody Phillips
*  Company: Phillips Data
*  Website: www.phpaes.com, www.phillipsdata.com
*  File: AES.class.php
*  October 1, 2007
*
*  This software is sold as-is without any warranties, expressed or implied,
*  including but not limited to performance and/or merchantability. No
*  warranty of fitness for a particular purpose is offered. This script can
*  be used on as many servers as needed, as long as the servers are owned
*  by the purchaser. (Contact us if you want to distribute it as part of
*  another project) The purchaser cannot modify, rewrite, edit, or change any
*  of this code and then resell it, which would be copyright infringement.
*  This code can be modified for personal use only.
*
*  Comments, Questions? Contact the author at cody [at] wshost [dot] net
*/

class Thaind_Models_AES {
	var $_iv = "thaindivco16kytu";
	var $_key = "thaindkeyco16chu";
	function __construct($key = null,$iv = null){
		if ($iv){
			if (is_array($iv)){
				$this->_iv = "";
				foreach ($iv as $chr) {
			    	$this->_iv .= chr($chr);
				}
			}else{
				$this->_iv = $iv;
			}
		}
		if ($key){
			if (is_array($key)){
				$this->_key = "";
				foreach ($key as $chr) {
			    	$this->_key .= chr($chr);
				}
			}else{
				$this->_key = $key;
			}
		}
	}
	function aes128Encrypt($data,$key = null,$iv = null) {
		if (is_null($key)){
			$key = $this->_key;
		}
		if (is_null($iv)){
			$iv = $this->_iv;
		}
		$block = mcrypt_get_block_size('rijndael_128', 'cbc');
		$pad = $block - (strlen($data) % $block);
		$data .= str_repeat(chr($pad), $pad);
		return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC,$iv));
	}
	function aes128Decrypt($data,$key = null,$iv = null) {
		$data = base64_decode($data);
		if (is_null($key)){
			$key = $this->_key;
		}
		if (is_null($iv)){
			$iv = $this->_iv;
		}		
		$data = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC,$iv);
		$block = mcrypt_get_block_size('rijndael_128', 'cbc');
		$pad = ord($data[($len = strlen($data)) - 1]);
		$len = strlen($data);
		$pad = ord($data[$len-1]);
		return substr($data, 0, strlen($data) - $pad);
	}
}